use tui::style::Color;
use crate::pet_config::{CatBreed, OctopusType, PetType, MoodState};
use rand::Rng;
use std::time::{Duration, Instant};

#[derive(Clone)]
pub struct PetFrame {
    pub text: String,
    pub color: Option<Color>,
}

// 宠物动画trait
pub trait PetAnimation {
    fn get_idle_frames(&self) -> Vec<Vec<PetFrame>>;
    fn get_running_frames(&self) -> Vec<Vec<PetFrame>>;
    fn get_sleep_frame(&self) -> Vec<PetFrame>;
    fn get_mood_frame(&self, mood_state: MoodState) -> Vec<PetFrame>;
    fn get_colors(&self) -> (Color, Color, Color);
    fn as_any(&self) -> &dyn std::any::Any;
}

// 猫咪动画器
pub struct CatAnimator {
    breed: CatBreed,
}

impl CatAnimator {
    pub fn new(breed: CatBreed) -> Self {
        Self { breed }
    }
}

impl PetAnimation for CatAnimator {
    fn get_idle_frames(&self) -> Vec<Vec<PetFrame>> {
        let (primary_color, secondary_color, accent_color) = self.breed.get_colors();
        
        vec![
            vec![
                PetFrame { text: r" /\_/\ ".to_string(), color: Some(primary_color) },
                PetFrame { text: "( o.o )".to_string(), color: Some(secondary_color) },
                PetFrame { text: " > ^ < ".to_string(), color: Some(accent_color) },
            ],
            vec![
                PetFrame { text: r" /\_/\ ".to_string(), color: Some(primary_color) },
                PetFrame { text: "( >.< )".to_string(), color: Some(secondary_color) },
                PetFrame { text: " > ^ < ".to_string(), color: Some(accent_color) },
            ],
        ]
    }
    
    fn get_running_frames(&self) -> Vec<Vec<PetFrame>> {
        let (primary_color, secondary_color, accent_color) = self.breed.get_colors();
        
        vec![
            vec![
                PetFrame { text: r" /\_/\ ".to_string(), color: Some(primary_color) },
                PetFrame { text: "( -.- )".to_string(), color: Some(secondary_color) },
                PetFrame { text: " > ^ < ".to_string(), color: Some(accent_color) },
            ],
            vec![
                PetFrame { text: r" /\_/\ ".to_string(), color: Some(primary_color) },
                PetFrame { text: "( o.o )".to_string(), color: Some(secondary_color) },
                PetFrame { text: " > ^ < ".to_string(), color: Some(accent_color) },
            ],
        ]
    }
    
    fn get_sleep_frame(&self) -> Vec<PetFrame> {
        let (primary_color, secondary_color, accent_color) = self.breed.get_colors();
        
        vec![
            PetFrame { text: r" /\_/\ ".to_string(), color: Some(primary_color) },
            PetFrame { text: "( -.- )".to_string(), color: Some(secondary_color) },
            PetFrame { text: " zzz.. ".to_string(), color: Some(accent_color) },
        ]
    }
    
    fn get_mood_frame(&self, mood_state: MoodState) -> Vec<PetFrame> {
        let (primary_color, secondary_color, accent_color) = self.breed.get_colors();
        
        let face = match mood_state {
            MoodState::VeryHappy => "( ^vv^ )",
            MoodState::Happy => "( ovo )",
            MoodState::Normal => "( -.- )",
            MoodState::Unhappy => "( u.u )",
            MoodState::VeryUnhappy => "( T.T )",
            MoodState::Depressed => "( x.x )",
            MoodState::Sleeping => "( -.- )",
        };
        
        vec![
            PetFrame { text: r" /\_/\ ".to_string(), color: Some(primary_color) },
            PetFrame { text: face.to_string(), color: Some(secondary_color) },
            PetFrame { text: " > ^ < ".to_string(), color: Some(accent_color) },
        ]
    }
    
    fn get_colors(&self) -> (Color, Color, Color) {
        self.breed.get_colors()
    }
    
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

// 章鱼动画器
pub struct OctopusAnimator {
    octopus_type: OctopusType,
}

impl OctopusAnimator {
    pub fn new(octopus_type: OctopusType) -> Self {
        Self { octopus_type }
    }
}

impl PetAnimation for OctopusAnimator {
    fn get_idle_frames(&self) -> Vec<Vec<PetFrame>> {
        let (primary_color, secondary_color, accent_color) = self.octopus_type.get_colors();
        
        vec![
            vec![
                PetFrame { text: "   -----   ".to_string(), color: Some(primary_color) },
                PetFrame { text: "  ( • ε • ) ".to_string(), color: Some(secondary_color) },
                PetFrame { text: r"  / \ o / \   ".to_string(), color: Some(accent_color) },
                // PetFrame { text: r"  /  \   ".to_string(), color: Some(accent_color) },
            ],
            vec![
                PetFrame { text: "    -----   ".to_string(), color: Some(primary_color) },
                PetFrame { text: "  ( • 3 • ) ".to_string(), color: Some(secondary_color) },
                PetFrame { text: r"  / \ o / \   ".to_string(), color: Some(accent_color) },
                // PetFrame { text: r"  /   \   ".to_string(), color: Some(accent_color) },
            ],
        ]
    }
    
    fn get_running_frames(&self) -> Vec<Vec<PetFrame>> {
        let (primary_color, secondary_color, accent_color) = self.octopus_type.get_colors();
        
        vec![
            vec![
                PetFrame { text: "    -----   ".to_string(), color: Some(primary_color) },
                PetFrame { text: "  ( • ε • ) ".to_string(), color: Some(secondary_color) },
                PetFrame { text: r"  / \ o / \   ".to_string(), color: Some(accent_color) },
                
            ],
            vec![
                PetFrame { text: "    -----   ".to_string(), color: Some(primary_color) },
                PetFrame { text: "  ( • ε • ) ".to_string(), color: Some(secondary_color) },
                PetFrame { text: r"  \ / o \ /   ".to_string(), color: Some(accent_color) },
                
            ],
        ]
    }
    
    fn get_sleep_frame(&self) -> Vec<PetFrame> {
        let (primary_color, secondary_color, accent_color) = self.octopus_type.get_colors();
        
        vec![
            PetFrame { text: "   -----   ".to_string(), color: Some(primary_color) },
            PetFrame { text: "  (  - - - ) ".to_string(), color: Some(secondary_color) },
            PetFrame { text: r"   / \ o/ \   ".to_string(), color: Some(accent_color) },
            PetFrame { text: "  zzz...   ".to_string(), color: Some(accent_color) },
        ]
    }
    
    fn get_mood_frame(&self, mood_state: MoodState) -> Vec<PetFrame> {
        let (primary_color, secondary_color, accent_color) = self.octopus_type.get_colors();
        
        let face = match mood_state {
            MoodState::VeryHappy => "  ( • ε • ) ",
            MoodState::Happy => "  ( • ε • ) ",
            MoodState::Normal => "  ( • - • ) ",
            MoodState::Unhappy => "  ( • ~ • ) ",     // 有点不开心
            MoodState::VeryUnhappy => "  ( >。ε<。) ",  // 哭泣的表情
            MoodState::Depressed => "  ( >。ε<。) ",    // 垂头丧气时也哭泣
            MoodState::Sleeping => "  ( • - • ) ",
        };
        
        vec![
            PetFrame { text: "   -----   ".to_string(), color: Some(primary_color) },
            PetFrame { text: face.to_string(), color: Some(secondary_color) },
            PetFrame { text: r"  / \ o / \   ".to_string(), color: Some(accent_color) },
            //  PetFrame { text: r"   / \   ".to_string(), color: Some(accent_color) },
        ]
    }
    
    fn get_colors(&self) -> (Color, Color, Color) {
        self.octopus_type.get_colors()
    }
    
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl OctopusAnimator {
    
    // 章鱼吃东西的动画，嘴巴在O和-之间变化
    pub fn get_eating_frames(&self) -> Vec<Vec<PetFrame>> {
        let (primary_color, secondary_color, accent_color) = self.octopus_type.get_colors();
        
        vec![
            vec![
                PetFrame { text: "    -----   ".to_string(), color: Some(primary_color) },
                PetFrame { text: "  ( • O • ) ".to_string(), color: Some(secondary_color) },
                PetFrame { text: r"  / \ o / \  ".to_string(), color: Some(accent_color) },
            ],
            vec![
                PetFrame { text: "    -----   ".to_string(), color: Some(primary_color) },
                PetFrame { text: "  ( • ε • ) ".to_string(), color: Some(secondary_color) },
                PetFrame { text: r"  / \ o / \  ".to_string(), color: Some(accent_color) },
            ],
        ]
    }
    
    // 章鱼哭泣动画，从有泪珠到没有泪珠
    pub fn get_crying_frames(&self) -> Vec<Vec<PetFrame>> {
        let (primary_color, secondary_color, accent_color) = self.octopus_type.get_colors();
        
        vec![
            vec![
                PetFrame { text: "   -----   ".to_string(), color: Some(primary_color) },
                PetFrame { text: "  ( >。ε<。) ".to_string(), color: Some(secondary_color) },
                PetFrame { text: r"  / \ o / \  ".to_string(), color: Some(accent_color) },
            ],
            vec![
                PetFrame { text: "   -----   ".to_string(), color: Some(primary_color) },
                PetFrame { text: "  ( > ε < ) ".to_string(), color: Some(secondary_color) },
                PetFrame { text: r"  / \ o / \  ".to_string(), color: Some(accent_color) },
            ],
        ]
    }
}

// 宠物动画管理器
pub struct PetAnimationManager {
    animator: Box<dyn PetAnimation>,
    frames: Vec<Vec<PetFrame>>,
    current_frame: usize,
    last_update: Instant,
    update_interval: Duration,
    x: u16,
    y: u16,
    target_x: u16,
    target_y: u16,
    is_moving: bool,
    last_move_time: Instant,
    move_interval: Duration,
    running_frames: Vec<Vec<PetFrame>>,
    reaction_frame: Option<Vec<PetFrame>>,
    reaction_timer: Option<Instant>,
    is_crying: bool,
    special_animation_timer: Option<Instant>,
    special_animation_type: Option<MoodState>,
}

impl PetAnimationManager {
    pub fn new(pet_type: PetType) -> Self {
        let animator: Box<dyn PetAnimation> = match pet_type {
            PetType::Cat(breed) => Box::new(CatAnimator::new(breed)),
            PetType::Octopus(octopus_type) => Box::new(OctopusAnimator::new(octopus_type)),
        };
        
        let frames = animator.get_idle_frames();
        let running_frames = animator.get_running_frames();
        
        Self {
            animator,
            frames,
            current_frame: 0,
            last_update: Instant::now(),
            update_interval: Duration::from_millis(500),
            x: 40,
            y: 12,
            target_x: 40,
            target_y: 12,
            is_moving: false,
            last_move_time: Instant::now(),
            move_interval: Duration::from_secs(3),
            running_frames,
            reaction_frame: None,
            reaction_timer: None,
            is_crying: false,
            special_animation_timer: None,
            special_animation_type: None,
        }
    }
    
    pub fn update(&mut self, can_move: bool, is_sleeping: bool, mood_state: MoodState) {
        let now = Instant::now();
        // 清理过期的反应动画
        self.clear_expired_reaction();
        // 清理过期的特殊动画
        self.clear_expired_special_animation(&mood_state);
        // 处理移动逻辑
        if can_move && !is_sleeping && !self.is_crying && self.special_animation_timer.is_none() {
            if !self.is_moving && now.duration_since(self.last_move_time) >= self.move_interval {
                self.start_random_movement();
            }
            if self.is_moving {
                self.move_towards_target();
            }
        } else {
            self.is_moving = false;
        }
        if !self.is_moving {
            if self.special_animation_timer.is_none() {
                match mood_state {
                    MoodState::VeryUnhappy | MoodState::Depressed => {
                        self.is_crying = true;
                        self.frames = if let Some(octopus_animator) = self.animator.as_any().downcast_ref::<OctopusAnimator>() {
                            octopus_animator.get_crying_frames()
                        } else {
                            self.animator.get_idle_frames()
                        };
                    }
                    _ => {
                        self.is_crying = false;
                        self.frames = self.get_mood_based_frames(mood_state);
                    }
                }
            } else if let Some(special_mood) = &self.special_animation_type {
                self.frames = self.get_mood_based_frames(special_mood.clone());
            }
        }
        if now.duration_since(self.last_update) >= self.update_interval {
            self.current_frame = (self.current_frame + 1) % self.frames.len();
            self.last_update = now;
        }
    }
    
    fn start_random_movement(&mut self) {
        let mut rng = rand::thread_rng();
        
        // 随机选择新的目标位置
        self.target_x = rng.gen_range(5..75);
        self.target_y = rng.gen_range(5..20);
        
        self.is_moving = true;
        // 只有在不哭泣时才切换到跑步动画
        if !self.is_crying {
            self.frames = self.running_frames.clone();
        }
        self.last_move_time = Instant::now();
    }
    
    fn move_towards_target(&mut self) {
        let dx = if self.target_x > self.x { 1 } else if self.target_x < self.x { -1 } else { 0 };
        let dy = if self.target_y > self.y { 1 } else if self.target_y < self.y { -1 } else { 0 };
        
        if dx != 0 {
            self.x = (self.x as i16 + dx) as u16;
        }
        if dy != 0 {
            self.y = (self.y as i16 + dy) as u16;
        }
        
        // 检查是否到达目标
        if self.x == self.target_x && self.y == self.target_y {
            self.is_moving = false;
            // 只有在不哭泣时才切换回idle动画
            if !self.is_crying {
                self.frames = self.animator.get_idle_frames();
            }
        }
    }
    
    pub fn get_current_frame(&self) -> &Vec<PetFrame> {
        &self.frames[self.current_frame]
    }
    
    pub fn get_sleep_frame(&self) -> Vec<PetFrame> {
        self.animator.get_sleep_frame()
    }
    

    
    pub fn get_position(&self) -> (u16, u16) {
        (self.x, self.y)
    }
    
    pub fn is_moving(&self) -> bool {
        self.is_moving
    }
    
    pub fn is_crying(&self) -> bool {
        self.is_crying
    }
    
    fn get_mood_based_frames(&self, mood_state: MoodState) -> Vec<Vec<PetFrame>> {
        // 根据心情状态生成相应的动画帧
        if let Some(octopus_animator) = self.animator.as_any().downcast_ref::<OctopusAnimator>() {
            // 章鱼根据心情状态使用不同的动画
            match mood_state {
                MoodState::VeryHappy => {
                    // 检查是否是喂食动画（通过special_animation_timer判断）
                    if self.special_animation_timer.is_some() {
                        octopus_animator.get_eating_frames() // 喂食时播放吃东西动画
                    } else {
                        // 普通VeryHappy状态使用表情动画，创建两帧动画
                         let mood_frame = octopus_animator.get_mood_frame(mood_state);
                         let face2 = "  ( • ♥ • ) ";
                         let (primary_color, secondary_color, accent_color) = octopus_animator.get_colors();
                         let happy_frame = vec![
                             PetFrame { text: "    -----   ".to_string(), color: Some(primary_color) },
                             PetFrame { text: face2.to_string(), color: Some(secondary_color) },
                             PetFrame { text: r"   / \ o/ \   ".to_string(), color: Some(accent_color) },
                         ];
                         vec![mood_frame, happy_frame]
                    }
                }
                MoodState::VeryUnhappy | MoodState::Depressed => octopus_animator.get_crying_frames(), // 很不开心或垂头丧气时哭泣
                _ => {
                    // 其他状态使用对应心情的表情动画，创建两帧动画
                    let mood_frame = octopus_animator.get_mood_frame(mood_state);
                    vec![mood_frame.clone(), mood_frame]
                }
            }
        } else {
            // 对于猫咪，使用心情状态帧，提供两帧相同的动画以保持兼容性
            let mood_frame = self.animator.get_mood_frame(mood_state);
            vec![mood_frame.clone(), mood_frame]
        }
    }
     
    pub fn add_reaction_animation(&mut self) {
        // 简单的反应动画，设置2秒的反应时间
        self.reaction_timer = Some(Instant::now() + Duration::from_secs(2));
    }
    
    // 添加哭泣动画
    pub fn start_crying_animation(&mut self) {
        if let Some(octopus_animator) = self.animator.as_any().downcast_ref::<OctopusAnimator>() {
            self.frames = octopus_animator.get_crying_frames();
            self.current_frame = 0;
            self.last_update = Instant::now(); // 重置动画时间
            self.is_moving = false; // 哭泣时停止移动
            self.is_crying = true; // 设置哭泣状态
        }
    }
    
    // 停止哭泣动画，恢复正常状态
    pub fn stop_crying_animation(&mut self) {
        self.frames = self.animator.get_idle_frames();
        self.current_frame = 0;
        self.last_update = Instant::now(); // 重置动画时间
        self.is_crying = false; // 取消哭泣状态
    }
    
    // 开始喂食动画（可指定持续秒数）
    pub fn start_eating_animation_with_duration(&mut self, seconds: u64) {
        if let Some(octopus_animator) = self.animator.as_any().downcast_ref::<OctopusAnimator>() {
            self.frames = octopus_animator.get_eating_frames();
            self.current_frame = 0;
            self.last_update = Instant::now(); // 重置动画时间
            self.is_moving = false; // 吃东西时停止移动
            // 设置喂食动画定时器，持续seconds秒
            self.special_animation_timer = Some(Instant::now() + Duration::from_secs(seconds));
            self.special_animation_type = Some(MoodState::VeryHappy); // 使用VeryHappy作为吃东西动画的标识
        }
    }
    
    // 保留原有3秒版本，兼容旧调用
    pub fn start_eating_animation(&mut self) {
        self.start_eating_animation_with_duration(3);
    }
     
    pub fn get_current_display_frame(&self) -> &Vec<PetFrame> {
        // 检查是否有反应动画正在播放
        if let (Some(reaction_frame), Some(timer)) = (&self.reaction_frame, self.reaction_timer) {
            if Instant::now() < timer {
                return reaction_frame;
            }
        }
        
        // 否则返回正常的当前帧
        self.get_current_frame()
    }
     
    pub fn clear_expired_reaction(&mut self) {
        if let Some(timer) = self.reaction_timer {
            if Instant::now() >= timer {
                self.reaction_frame = None;
                self.reaction_timer = None;
            }
        }
    }
    
    pub fn clear_expired_special_animation(&mut self, mood_state: &MoodState) {
        if let Some(timer) = self.special_animation_timer {
            if Instant::now() >= timer {
                self.special_animation_timer = None;
                self.special_animation_type = None;
                match mood_state {
                    MoodState::VeryUnhappy | MoodState::Depressed => {
                        self.is_crying = true;
                        if let Some(octopus_animator) = self.animator.as_any().downcast_ref::<OctopusAnimator>() {
                            self.frames = octopus_animator.get_crying_frames();
                        }
                    }
                    _ => {
                        self.is_crying = false;
                        self.frames = self.get_mood_based_frames(mood_state.clone());
                    }
                }
            }
        }
    }
}